import { getReadCardToken, getCardInfo } from "@/api/common/other/index";

//const default_url = "ws://192.168.110.14:21802/reader";
const default_url = "ws://127.0.0.1:21802/reader";

const errorEvent = (event: any) => {
  console.log(event);
  if (!event) {
    console.log("读卡失败!", event);
    return;
  }
  if (event.type == "error") {
    ElMessage.error("读卡失败!请检查设备连接!");
  }
  ElMessageBox({
    title: "程序下载",
    showCancelButton: true,
    showConfirmButton: false,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    message: () =>
      h(
        "div",
        {
          style: {},
        },
        [
          h(
            "span",
            {
              style: {
                color: "red",
              },
            },
            `未检测到身份证阅读器守护程序，请打开程序或点击下面链接重新下载。`
          ),
          h("br", undefined, undefined),
          h(
            "span",
            {
              style: {
                color: "red",
              },
            },
            "程序下载地址"
          ),
          h(
            "a",
            {
              href: "/app/download/SmzTestCardReader_Setup.exe",
              target: "_blank",
              download: "CardReaderSetup.exe",
              style: {
                color: "blue",
                textDecoration: "underline",
              },
            },
            "点击下载"
          ),
          h("br", undefined, undefined),
          h(
            "span",
            {
              style: {
                color: "red",
              },
            },
            "驱动下载地址"
          ),
          h(
            "a",
            {
              href: "/app/download/CardDrive.rar",
              target: "_blank",
              download: "CardDrive.rar",
              style: {
                color: "blue",
                textDecoration: "underline",
              },
            },
            "点击下载"
          ),

          h("br", undefined, undefined),
          h(
            "span",
            {
              style: {
                color: "red",
              },
            },
            "有关读卡器守护程序使用教程请"
          ),
          h(
            "a",
            {
              href: "/app/tutorial.html",
              target: "_blank",
              style: {
                color: "blue",
                textDecoration: "underline",
              },
            },
            "点击查看"
          ),
        ]
      ),
  });
};

export function CardDeviceSocketPromise(corpCode?: string) {
  return new Promise((resolve, reject) => {
    const socket = new WebSocket(default_url);
    let token = "";
    socket.onerror = (event: any) => {
      errorEvent(event);
      reject(event);
    };
    socket.close = (event: any) => {
      errorEvent(event);
      reject(event);
    };
    socket.onopen = () => {
      if (socket.readyState === 1) {
        getReadCardToken(corpCode)
          .then((res) => {
            if (res.type == 0 && res.success) {
              token = res.data;
              socket.send(`read:${res.data}:smz`);
            } else {
              reject();
            }
          })
          .catch(() => {
            reject();
          });
      } else {
        ElMessage({
          type: "warning",
          message: "请检查设备连接!",
        });
        reject();
      }
    };
    socket.onmessage = async (e: any) => {
      let result = JSON.parse(e.data);
      if (result.success) {
        getCardInfo(token)
          .then((res) => {
            if (res.type == 0 && res.success) {
              console.log(res.data);
              res.data.token = token;
              resolve(res.data);
            } else {
              reject();
            }
          })
          .catch(() => {
            reject();
          })
          .finally(() => {
            socket.close();
          });
      } else {
        ElMessage.error(result.msg);
        reject();
      }
    };
  });
}
